<template>
  <div id="body">
    <el-card id="tableCrad">
      <div slot="header" class="clearfix">
        <span>用户管理</span>
      </div>
      <el-row id="btnRow" type="flex" style="width: 100%">
        <el-col :span="20">
          <el-row type="flex">
            <el-tooltip content="用户编号" placement="top" effect="light">
              <el-input
                class="input"
                v-model="code"
                placeholder="请输入用户编号"
                clearable
                style="margin-right: 10px; width: 16%"
              ></el-input>
            </el-tooltip>
            <el-tooltip content="用户账号" placement="top" effect="light">
              <el-input
                class="input"
                v-model="phone"
                placeholder="请输入用户账号"
                clearable
                style="margin-right: 10px; width: 16%"
              ></el-input>
            </el-tooltip>
            <el-tooltip content="用户姓名" placement="top" effect="light">
              <el-input
                class="input"
                v-model="name"
                placeholder="请输入用户姓名"
                clearable
                style="margin-right: 10px; width: 16%"
              ></el-input>
            </el-tooltip>
            <el-tooltip content="用户角色" placement="top" effect="light">
              <el-select
                v-model="ruleCode"
                @change="getPages"
                placeholder="请选择用户角色"
                style="margin-right: 10px; width: 16%"
                filterable
              >
                <el-option
                  v-for="item in ruleOptions"
                  :key="item.code.toString()"
                  :label="item.title"
                  :value="item.code.toString()"
                >
                </el-option>
              </el-select>
            </el-tooltip>
            <el-tooltip content="所属单位" placement="top" effect="light">
              <el-select
                v-model="entCode"
                @change="getPages"
                placeholder="请选择所属单位"
                style="margin-right: 10px; width: 16%"
                filterable
              >
                <el-option
                  v-for="item in selectPNodeOptions"
                  :key="item.code.toString()"
                  :label="item.title"
                  :value="item.code.toString()"
                >
                </el-option>
              </el-select>
            </el-tooltip>
            <el-tooltip content="用户状态" placement="top" effect="light">
              <el-select
                v-model="deleted"
                @change="getPages"
                placeholder="请选择用户状态"
                style="margin-right: 10px; width: 16%"
              >
                <el-option label="全部" :value="-1"></el-option>
                <el-option label="可用" :value="0"></el-option>
                <el-option label="禁用" :value="1"></el-option>
              </el-select>
            </el-tooltip>
            <el-button
              @click="getPages"
              icon="el-icon-search"
              circle
            ></el-button>
          </el-row>
        </el-col>
        <el-col :span="2" :offset="2">
          <el-row>
            <el-button
              @click="addOpen"
              type="primary"
              icon="el-icon-plus"
              circle
            ></el-button>
            <el-button
              @click="deleteBatch"
              type="danger"
              icon="el-icon-delete"
              circle
            ></el-button>
          </el-row>
        </el-col>
      </el-row>
      <el-table
        ref="multipleTable"
        :data="tableData"
        style="width: 100%"
        :height="tableHeight"
      >
        <el-table-column type="selection" fixed="left"> </el-table-column>
        <el-table-column type="expand" fixed="left">
          <template slot-scope="props">
            <el-form label-position="left" inline class="demo-table-expand">
              <el-form-item label="姓名">
                <span>{{ props.row.name }}</span>
              </el-form-item>
              <el-form-item label="头像">
                <img :src="baseURL + props.row.avatar" width="50" height="50" />
              </el-form-item>
              <el-form-item label="性别">
                <span>{{ props.row.gender == 1 ? "男" : "女" }}</span>
              </el-form-item>
              <el-form-item label="年龄">
                <span>{{ getAgeByBirth(props.row.birth) }}</span>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column fixed prop="id" label="id" width="80" v-if="false">
        </el-table-column>
        <el-table-column fixed prop="code" label="编号" width="150">
        </el-table-column>
        <el-table-column
          prop="phone"
          label="账号"
          width="110"
        ></el-table-column>
        <el-table-column prop="name" label="姓名" align="center">
        </el-table-column>
        <el-table-column
          prop="ruleName"
          label="角色"
          width="110"
          align="center"
        >
          <template slot-scope="scope">
            <span>{{
              isStrEmpty(scope.row.ruleCode) ? "无" : scope.row.ruleName
            }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="entName" label="单位" align="center">
          <template slot-scope="scope">
            <span>{{
              isStrEmpty(scope.row.entCode) ? "无" : scope.row.entName
            }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="pwd"
          label="密码（已加密）"
          width="120"
          show-overflow-tooltip
          v-if="false"
        >
        </el-table-column>
        <el-table-column prop="deleted" label="账户状态" width="80">
          <template slot-scope="scope">
            <el-tag
              :type="scope.row.deleted === 0 ? 'success' : 'danger'"
              disable-transitions
              >{{ scope.row.deleted === 0 ? "可用" : "禁用" }}</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" align="center">
          <template slot-scope="scope">
            <el-button
              @click.native.prevent="editOpen(scope.row)"
              type="text"
              size="small"
            >
              编辑
            </el-button>
            <el-button
              @click.native.prevent="deleteRow(scope.row)"
              type="text"
              style="color: red"
              size="small"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        id="pageDevice"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="paginationData.currentPage"
        :page-sizes="[10, 20, 50]"
        :page-size="paginationData.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="paginationData.total"
      >
      </el-pagination>
    </el-card>
    <!-- 编辑弹窗开始 -->
    <el-dialog
      title="编辑"
      :visible.sync="editDialogVisible"
      width="30%"
      :before-close="editClose"
      v-loading="loading"
    >
      <el-form ref="editForm" :rules="rules" :model="row" label-width="80px">
        <el-form-item label="id" prop="id" v-if="false">
          <el-input type="text" disabled v-model="row.id"></el-input>
        </el-form-item>
        <el-form-item label="用户编号" prop="code">
          <el-input type="text" disabled v-model="row.code"></el-input>
        </el-form-item>
        <el-form-item label="账号" prop="phone">
          <el-input
            type="text"
            placeholder="请输入手机号码"
            v-model="row.phone"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户名" prop="name">
          <el-input
            type="text"
            placeholder="请输入用户名"
            v-model="row.name"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input
            type="text"
            placeholder="无输入，则不修改"
            v-model="row.pwd"
          ></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="row.gender" placeholder="请选择用户性别">
            <el-option label="男" :value="1"></el-option>
            <el-option label="女" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="出生日期" prop="birth">
          <el-date-picker
            v-model="row.birth"
            type="date"
            placeholder="选择日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="角色" prop="ruleCode">
          <el-select v-model="row.ruleCode" placeholder="请选择用户角色" filterable>
            <el-option
              v-for="item in validRuleOptions"
              :key="item.code"
              :label="item.title"
              :value="item.code"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="单位" prop="entCode">
          <el-select v-model="row.entCode" placeholder="请选择用户单位" filterable>
            <el-option
              v-for="item in selectPNodeOptions"
              :key="item.code.toString()"
              :label="item.title"
              :value="item.code.toString()"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="deleted">
          <el-select v-model="row.deleted" placeholder="请选择用户状态">
            <el-option label="可用" :value="0"></el-option>
            <el-option label="禁用" :value="1"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editClose">取 消</el-button>
        <el-button type="primary" @click="editConfirm">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑弹窗结束 -->
    <!-- 增加弹窗开始 -->
    <el-dialog
      title="增加"
      :visible.sync="addDialogVisible"
      width="30%"
      :before-close="addClose"
      v-loading="loading"
    >
      <el-form ref="addForm" :rules="rules" :model="row" label-width="80px">
        <el-form-item label="账号" prop="phone">
          <el-input
            type="text"
            placeholder="请输入手机号码"
            v-model="row.phone"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户名" prop="name">
          <el-input
            type="text"
            placeholder="请输入用户名"
            v-model="row.name"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="pwd">
          <el-input
            type="text"
            placeholder="输入密码，系统将会自动加密"
            v-model="row.pwd"
          ></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="row.gender" placeholder="请选择用户性别">
            <el-option label="男" :value="1"></el-option>
            <el-option label="女" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="出生日期" prop="birth">
          <el-date-picker
            v-model="row.birth"
            type="date"
            placeholder="选择日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="角色" prop="ruleCode">
          <el-select v-model="row.ruleCode" placeholder="请选择用户角色" filterable>
            <el-option
              v-for="item in validRuleOptions"
              :key="item.code"
              :label="item.title"
              :value="item.code"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="单位" prop="entCode">
          <el-select v-model="row.entCode" placeholder="请选择用户单位" filterable>
            <el-option
              v-for="item in selectPNodeOptions"
              :key="item.code.toString()"
              :label="item.title"
              :value="item.code.toString()"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="deleted">
          <el-select v-model="row.deleted" placeholder="请选择用户状态">
            <el-option label="可用" :value="0"></el-option>
            <el-option label="禁用" :value="1"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addClose">取 消</el-button>
        <el-button type="primary" @click="addConfirm">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 增加弹窗结束 -->
  </div>
</template>

<script>
import { baseURL } from "@/api/request";
import { countAgeByBirth, isStrEmpty } from "@/utils/util";
export default {
  data() {
    return {
      //表格高度
      tableHeight: window.innerHeight - 320,
      //头像基地址
      baseURL: baseURL,
      //分页参数
      tableData: [],
      paginationData: {
        pageSize: 10,
        currentPage: 1,
        total: 50,
      },
      //查询参数
      phone: "",
      name: "",
      code: "",
      deleted: -1,
      entCode: "-1",
      ruleCode: "-1",
      //修改或增加用到的的数据
      row: {},
      editDialogVisible: false,
      addDialogVisible: false,
      loading: false,
      rules: {
        pwd: [{ required: true, message: "请输入密码", trigger: "blur" }],
        name: [{ required: true, message: "请输入用户名", trigger: "blur" }],
        phone: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
          {
            min: 11,
            max: 11,
            pattern: new RegExp(/^\d{11}$/, "g"),
            message: "请输入11位手机号码",
            trigger: "blur",
          },
        ],
        deleted: [{ required: true, message: "请选择状态", trigger: "change" }],
      },
      ruleOptions: [],
      selectPNodeOptions: [],
    };
  },
  methods: {
    handleSizeChange(val) {
      this.paginationData.pageSize = val;
      this.getPages();
    },
    handleCurrentChange(val) {
      this.paginationData.currentPage = val;
      this.getPages();
    },
    getPages() {
      //axios请求方式，通过this.request使用分装好的axios实例
      this.request
        .get("/user/getPage", {
          params: {
            phone: this.phone,
            name: this.name,
            code: this.code,
            ruleCode: this.ruleCode,
            entCode: this.entCode,
            deleted: this.deleted,
            currentPage: this.paginationData.currentPage,
            pageSize: this.paginationData.pageSize,
          },
        })
        .then((res) => {
          if (res.code == 200) {
            this.tableData = res.data.records;
            this.paginationData.total = res.data.total;
            this.paginationData.currentPage = res.data.current;
            this.paginationData.pageSize = res.data.size;
          } else if (res.code == 204) {
            this.tableData = []; // 清空表格数据
            this.paginationData.total = 0; // 总记录数置为0
            this.paginationData.currentPage = 1; // 当前页置为第一页
            this.paginationData.pageSize = 10; // 每页大小置为默认值
          } else {
            this.$message({
              message: res.msg,
              type: "error",
            });
          }
        });
    },
    getRuleOptions() {
      //axios请求方式，通过this.request使用分装好的axios实例
      this.request
        .get("/rule/getIndentOptions", {
          params: {
            parent: -1,
            deleted: 0,
          },
        })
        .then((res) => {
          if (res.code == 200) {
            this.ruleOptions = res.data;
            if (res.data[0].title == "根节点") {
              res.data[0].title = "全部";
            }
          } else {
            this.$message({
              message: res.msg,
              type: "error",
            });
          }
        });
    },
    getEntOptions() {
      this.request
        .get("/ent/getIndentOptions", {
          params: {
            parent: "-1",
            deleted: -1,
          },
        })
        .then((res) => {
          if (res.code == 200) {
            this.selectPNodeOptions = res.data;
            if (res.data[0].title == "根节点") {
              res.data[0].title = "全部";
            }
          } else {
            this.$message({
              message: res.msg,
              type: "error",
            });
          }
        });
    },
    editOpen(row) {
      this.row = {
        phone: row.phone,
        name: row.name,
        deleted: row.deleted,
        gender: row.gender,
        birth: row.birth,
        ruleCode: row.ruleCode,
        entCode: row.entCode,
        id: row.id,
        code: row.code,
      };
      this.editDialogVisible = true;
    },
    editClose() {
      this.$refs["editForm"].resetFields();
      this.resetRowParam();
      this.editDialogVisible = false;
    },
    editConfirm() {
      this.$refs["editForm"].validate((valid) => {
        if (valid) {
          this.$alert("是否确定编辑", "提示", {
            confirmButtonText: "确定",
            callback: (action) => {
              if (action == "confirm") {
                this.loading = true;
                this.request
                  .post("/user/update", {
                    id: this.row.id,
                    phone: this.row.phone,
                    name: this.row.name,
                    pwd: this.row.pwd,
                    gender: this.row.gender,
                    birth: this.row.birth,
                    ruleCode: this.row.ruleCode,
                    entCode: this.row.entCode,
                    deleted: this.row.deleted,
                  })
                  .then((res) => {
                    if (res.code == 200) {
                      this.$message({
                        message: res.msg,
                        type: "success",
                      });
                      this.editClose();
                      this.getPages();
                    } else {
                      this.$message({
                        message: res.msg,
                        type: "error",
                      });
                    }
                    this.loading = false;
                  })
                  .catch((err) => {
                    this.loading = false;
                  });
              }
            },
          });
        } else {
          this.$message({
            message: "请先规范填写表单信息",
            type: "warning",
          });
        }
      });
    },
    addOpen() {
      this.resetRowParam();
      this.addDialogVisible = true;
    },
    addClose() {
      this.$refs["addForm"].resetFields();
      this.resetRowParam();
      this.addDialogVisible = false;
    },
    addConfirm() {
      this.$refs["addForm"].validate((valid) => {
        if (valid) {
          this.$alert("是否确定新增", "提示", {
            confirmButtonText: "确定",
            callback: (action) => {
              if (action == "confirm") {
                this.loading = true;
                this.request
                  .post("/user/add", {
                    phone: this.row.phone,
                    name: this.row.name,
                    pwd: this.row.pwd,
                    gender: this.row.gender,
                    birth: this.row.birth,
                    ruleCode: this.row.ruleCode,
                    entCode: this.row.entCode,
                    deleted: this.row.deleted,
                  })
                  .then((res) => {
                    if (res.code == 200) {
                      this.$message({
                        message: res.msg,
                        type: "success",
                      });
                      this.addClose();
                      this.getPages();
                    } else {
                      this.$message({
                        message: res.msg,
                        type: "error",
                      });
                    }
                    this.loading = false;
                  })
                  .catch((err) => {
                    this.loading = false;
                  });
              }
            },
          });
        } else {
          this.$message({
            message: "请先规范填写表单信息",
            type: "warning",
          });
        }
      });
    },
    deleteRow(row) {
      this.$alert("是否确定删除", "提示", {
        confirmButtonText: "确定",
        callback: (action) => {
          if (action == "confirm") {
            this.request
              .post("/user/delete", {
                id: row.id,
              })
              .then((res) => {
                if (res.code == 200) {
                  this.$message({
                    message: res.msg,
                    type: "success",
                  });
                  this.getPages();
                } else {
                  this.$message({
                    message: res.msg,
                    type: "error",
                  });
                }
              });
          }
        },
      });
    },
    deleteBatch() {
      var selectedList = this.$refs.multipleTable.selection;
      if (selectedList.length <= 0) {
        this.$message({
          message: "请选择至少一条数据",
          type: "warning",
        });
        return;
      }
      var ids = [];
      for (var i = 0; i < selectedList.length; i++) {
        ids.push(selectedList[i].id);
      }
      this.$alert("是否确定删除", "提示", {
        confirmButtonText: "确定",
        callback: (action) => {
          //还没有做好判断 是否确定
          if (action == "confirm") {
            this.request
              .post("/user/deleteBatch", {
                ids: JSON.stringify(ids),
              })
              .then((res) => {
                if (res.code == 200) {
                  this.$message({
                    message: res.msg,
                    type: "success",
                  });
                  this.getPages();
                } else {
                  this.$message({
                    message: res.msg,
                    type: "error",
                  });
                }
              });
          }
        },
      });
    },
    getAgeByBirth: function (birth) {
      return countAgeByBirth(birth);
    },
    isStrEmpty: function (str) {
      return isStrEmpty(str);
    },
    resetRowParam() {
      this.row = {
        phone: '',
        name: '',
        deleted: '',
        gender: '',
        birth: '',
        ruleCode: '',
        entCode: '',
        id: '',
        code: '',
      };
    },
  },
  mounted() {
    window.addEventListener("resize", () => {
      this.tableHeight = window.innerHeight - 320;
    });
  },
  computed: {
    validRuleOptions() {
      // 在这里筛选您想要显示的选项
      return this.ruleOptions.filter((item) => {
        // 返回满足条件的选项
        return item.deleted == 0; // 仅返回deleted为0的选项
      });
    },
  },
  created() {
    //创建
    this.getPages();
    this.getRuleOptions();
    this.getEntOptions();
  },
};
</script>

<style scoped>
#body {
  display: flex;
  flex-direction: column;
  align-items: center;
}
#tableCrad {
  width: 100%;
}
#btnRow {
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}
#pageDevice {
  text-align: right;
}
.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}
.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}

.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  text-align: center;
  margin-bottom: 0;
  width: 24%;
}
</style>